/*
 * @Description:
 * @Version:
 * @Author: Troubadour
 * @Date: 2022-07-09 18:42:36
 * @LastEditors: Troubadour
 * @LastEditTime: 2022-07-10 10:55:36
 */

#include "hx711.h"

#define  CPU_FREQUENCY_MHZ    72		// STM32时钟主频


HX711_TypeDef HX711_Struct;

static void delay_us(__IO uint32_t delay)
{
    int last, curr, val;
    int temp;

    while (delay != 0)
    {
        temp = delay > 900 ? 900 : delay;
        last = SysTick->VAL;
        curr = last - CPU_FREQUENCY_MHZ * temp;
        if (curr >= 0)
        {
            do
            {
                val = SysTick->VAL;
            }
            while ((val < last) && (val >= curr));
        }
        else
        {
            curr += CPU_FREQUENCY_MHZ * 1000;
            do
            {
                val = SysTick->VAL;
            }
            while ((val <= last) || (val > curr));
        }
        delay -= temp;
    }
}


static uint32_t HX711_GetData(void)
{
    uint32_t count = 0;
    uint8_t i = 0;

    HX711_CLK_OUT(0);
    delay_us(1);

    while (HX711_DOU_IN);
    for(i=0; i<24; i++)
    {
        HX711_CLK_OUT(1);
        count <<= 1;
        delay_us(1);
        HX711_CLK_OUT(0);
        if(HX711_DOU_IN) count++;
        delay_us(1);
    }
    HX711_CLK_OUT(1);

    count ^= 0x800000; // 获得24位的数据，对0x800000异或相当于把最高位取反。
    delay_us(1);
    HX711_CLK_OUT(0);

    return count;
}


void HX711_GetWeight(void)
{
    static uint8_t count_filtter = 0;
    uint32_t data = HX711_GetData();
    if(data < HX711_Struct.Init_Value)
    {
        data = 0;
    }
    else
    {
        data -= HX711_Struct.Init_Value;
    }

    if(count_filtter++ >= HX711_WEIGHT_FILTER_VALUE-1)
    {
        HX711_Struct.Data = (HX711_Struct.Data + data) / HX711_WEIGHT_FILTER_VALUE;
        HX711_Struct.Ready = 1;
        count_filtter = 0;
    }
    else
    {
        HX711_Struct.Data += data;
    }
}

double HX711_GET_KG(uint32_t WeightData)
{
    return HX711_Struct.RelyValue * WeightData;
}


void HX711_Init(void)
{
#if HX711_INIT_FILTER_VALUE
    if(HX711_INIT_FILTER_VALUE)
    {
        for(i=0; i<HX711_INIT_FILTER_VALUE; i++)
        {
            HX711_Struct.Init_Value += HX711_GetData();
            HAL_Delay(80);
        }

        HX711_Struct.Init_Value = HX711_Struct.Init_Value / HX711_INIT_FILTER_VALUE;
    }
#else
    HX711_Struct.Init_Value = HX711_IN_VALUE;
#endif
    HX711_Struct.RelyValue = (HX711_Voltage / HX711_AdcBit) * HX711_UPPER;
}









